package com.zx._07_数据库.jdbc;

import com.github.javafaker.Faker;
import com.google.common.collect.Lists;
import com.zx.common.entity.UserData;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class 造数据3 {

    private static final int num = 1000 * 1000;

    public static void main(final String[] args) throws Exception {
        final List<UserData> list = Lists.newArrayListWithCapacity(num);
        final Faker fakerWithCN = new Faker(Locale.CHINA);// Locale.US  美国的数据
        for (int i = 1; i <= num; i++) {
            final UserData userInfo = new UserData();
            userInfo.setId(i * 1L);
            userInfo.setRealName(fakerWithCN.name().fullName());
            userInfo.setCellPhone(fakerWithCN.phoneNumber().cellPhone());
            userInfo.setCity(fakerWithCN.address().city());
            userInfo.setStreet(fakerWithCN.address().streetAddress());
            userInfo.setUniversityName(fakerWithCN.university().name());
            list.add(userInfo);
        }
        log.info("ready data");

        final long begin = System.currentTimeMillis();
        final List<List<UserData>> partition = Lists.partition(list, 5000);
        for (final List<UserData> list2 : partition) {
            save(list2);
        }

        log.info("done {}", (System.currentTimeMillis() - begin) / 1000);
    }

    public static void save(final List<UserData> list) {
        final Connection con = JDBC.getConnection();
        final String sql = "INSERT INTO t_member(id, real_name, cell_phone, university_name, city, street) VALUES(?, ?, ?, ?, ?, ?)";
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            for (final UserData user : list) {
                ps.setLong(1, user.getId());
                ps.setString(2, user.getRealName());
                ps.setString(3, user.getCellPhone());
                ps.setString(4, user.getUniversityName());
                ps.setString(5, user.getCity());
                ps.setString(6, user.getStreet());
                ps.addBatch();
            }
            ps.executeBatch();//执行批！
        } catch (final SQLException e) {
            e.printStackTrace();
        } finally {
            JDBC.release(con, ps, null);
        }
    }

}
